package com.douya.mvc.intercetor;

import com.douya.mvc.service.HttpLoggingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器
 *
 * @Author hcy
 * @Date 2024/3/22  10:05
 */
@Slf4j
public class LoggingInterceptor implements HandlerInterceptor {

    HttpLoggingService httpLoggingService;

    String applicationName;


    public LoggingInterceptor(HttpLoggingService httpLoggingService, String applicationName) {
        this.httpLoggingService = httpLoggingService;
        this.applicationName = applicationName;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute(applicationName + "beginTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        this.httpLoggingService.saveLog(request, response, handler);
    }
}
